package com.corecloud.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.corecloud.service.sms.ValidateCodeProcessor;
import com.corecloud.controller.sms.SmsCode;
import com.corecloud.entity.*;
import com.corecloud.mapper.mysql.SysLogMapper;
import com.corecloud.mapper.mysql.SysUserMapper;
import com.corecloud.mapper.mysql.SysUserRoleMapper;
import com.corecloud.service.AafUserService;
import com.corecloud.service.SysDeptService;
import com.corecloud.service.SysUserRoleService;
import com.corecloud.tools.LogEntryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Component
public class MyUserService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private AafUserService aafUserService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private LogEntryUtils logEntryUtils;

    /**
     * 通过手机号 mobile 去数据库里查找用户以及用户权限
     * @param mobile 手机号
     * @return
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByMobile(HttpServletRequest request, String mobile) throws UsernameNotFoundException {

        if(StringUtils.isEmpty(mobile)){ throw new UsernameNotFoundException("参数异常,请确认后登录"); }

        /**
         * 用户信息验证流程
         * 1：大唐数据库验证对应数据查询是否存在对应用户
         * 2：如果存在则直接使用大唐方面用户数据进行登录
         * 3：如不存在则查询本平台用户数据进行匹配
         */
        String pwd = "";
        //大唐用户数据验证获取
//		Map<String,Object> au = aafUserService.getInfoByUserName(username);
        Map<String,Object> au = new HashMap<>();
        SysUserEntity user = userMapper.selectOne(new QueryWrapper<SysUserEntity>().eq("phone",mobile));

        if((au == null || au.size() == 0) && user == null){//插入登录日志
            String logText = "用户名不存在！";
            logEntryUtils.sysLogS(logText, mobile);
            throw new UsernameNotFoundException(logText);
        }

        //大唐用户主体数据存在此用户，mysql库没有这个用户，需要添加此用户
        if(au != null && user == null){
            SysUserEntity newUser = new SysUserEntity();
            newUser.setUserName(mobile);
            newUser.setPassword(au.get("PASSWORD").toString());
            newUser.setIsValid(1);
            newUser.setCreateTime(new Date());
            newUser.setSource(3);
            if(!StringUtils.isEmpty(au.get("USER_NAME"))){
                newUser.setNickName(au.get("USER_NAME").toString().trim());
                newUser.setName(au.get("USER_NAME").toString().trim());
            }

            //回填用户机构与地区相关信息,如果查询不到机构则默认设置该用户为河南省用户
            if(!StringUtils.isEmpty(au.get("school"))){
                SysDeptEntity dept = sysDeptService.selectOne(new QueryWrapper<SysDeptEntity>().eq("dept_name",au.get("SCHOOL").toString().trim()));
                if(dept!=null && !StringUtils.isEmpty(dept.getDeptCode())){
                    newUser.setDeptId(dept.getId());
                }
                if(dept!=null && !StringUtils.isEmpty(dept.getAreaId())){
                    newUser.setAreaId(dept.getAreaId());
                }else{ newUser.setAreaId("410000"); }
            }else{ newUser.setAreaId("410000"); }

            //插入数据，新用户统一默认为教师角色
            try{
                userMapper.insert(newUser);
                user = userMapper.selectOne(new QueryWrapper<SysUserEntity>().eq("user_name",mobile));
                SysUserRoleEntity sur = new SysUserRoleEntity();
                sur.setRoleId(25);
                sur.setRoleState(1);
                sur.setRoleName("老师");
                sur.setRoleCode("TEACHER");
                sur.setUserId(newUser.getId());
                sysUserRoleService.insertInfo(sur);
            }catch (Exception e){ throw new UsernameNotFoundException("登录失败，请联系管理员"); }
        }

        //添加短信登陆用户的状态存入 session 中
        request.getSession().setAttribute(ValidateCodeProcessor.SESSION_KEY_LOGIN_TYPE.concat(user.getPhone()), "Y");
        //设置用户需要比对的密码
        SmsCode smsCode = (SmsCode)request.getSession().getAttribute(ValidateCodeProcessor.SESSION_KEY_PREFIX + mobile);
        pwd = smsCode.getCode();
        /*将该验证码删除
        * 删除验证码本该位于 SmsCodeFilter 下的 validate 方法最后一行，但由于此处需要密码认证所以改到这里*/
        request.getSession().removeAttribute(ValidateCodeProcessor.SESSION_KEY_PREFIX + mobile);

        List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
        List<SysUserRoleEntity> userRoleList =  userRoleMapper.selectList(new QueryWrapper<SysUserRoleEntity>().eq("user_id",user.getId()));
        List<String> authorityName = new ArrayList<>();
        for(int i = 0;i<userRoleList.size();i++){
            SysUserRoleEntity sr = userRoleList.get(i);
            if(sr.getRoleState() == 1){
                authorityName.add("ROLE_"+userRoleList.get(i).getRoleCode());
            }
        }
        for(String roleName : authorityName) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleName);
            auths.add(authority);
        }
        return new org.springframework.security.core.userdetails.User(user.getUserName(),pwd,true,true,true,true,auths);
    }
}
